package com.qilu.careprogram.controller.admin;

import com.alibaba.excel.util.StringUtils;
import com.qilu.careprogram.common.constant.MergeColumnsConstants;
import com.qilu.careprogram.model.Result;
import com.qilu.careprogram.pojo.dto.AnsQueDTO;
import com.qilu.careprogram.pojo.dto.AnswerDTO;
import com.qilu.careprogram.pojo.dto.UpdateIntervalDTO;
import com.qilu.careprogram.pojo.dto.UserDTO;
import com.qilu.careprogram.pojo.entity.PatientException;
import com.qilu.careprogram.pojo.entity.User;
import com.qilu.careprogram.pojo.vo.*;
import com.qilu.careprogram.service.PatientExceptionService;
import com.qilu.careprogram.service.PatientService;
import com.qilu.careprogram.service.QuestionService;
import com.qilu.careprogram.service.UserService;
import com.qilu.careprogram.utils.ExcelUtil;
import com.qilu.careprogram.utils.JwtUtil;
import com.qilu.careprogram.utils.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.time.LocalDateTime;

/**
 * @Description:医护端
 * @CreateTime: 2025-04-08  09:43
 * @Version: 1.0
 */
@RestController
@RequestMapping("/doctor")
@Slf4j
public class doctorController {
    @Resource
    private PatientService patientService;
    @Resource
    private QuestionService questionService;
    @Resource
    private PatientExceptionService patientExceptionService;
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/deletPatientInfoProstateCancerList")
    public Result<String> deletPatientInfoProstateCancerList(@RequestBody List<Long> ids) {
        patientService.deletePatientInfoProstateCancerList(ids);
        return Result.success("删除成功");
    }

    //    用于删除造口护理信息的接口
    @PostMapping("/deletReturnVisitList")
    public Result<String> deletReturnVisitList(@RequestBody List<Long> ids) {
        patientService.deleteReturnVisitList(ids);
        return Result.success("删除成功");
    }

    //获取护理信息填报数量
    @GetMapping("/getReturnVisitCountToday")
    public Result<Integer> getReturnVisitCountToday() {
        int reVisitsCount = patientService.getPatientReVisitsCountToday();
        return Result.success(reVisitsCount);
    }

    //获取全部护理信息
    @GetMapping("/getReturnVisitList")
    public Result<List<ReturnVisitVO>> getReturnVisitList(@RequestParam String hospitalNumber,
                                                          @RequestParam String gender,
                                                          @RequestParam String idCard,
                                                          @RequestParam String startTime,
                                                          @RequestParam String endTime) {
        return patientService.getReturnVisitList(hospitalNumber, gender, idCard, startTime, endTime);
    }

    // 获取全部前列腺癌症信息
    @GetMapping("/getPatientInfoProstateCancerList")
    public Result<List<ProstateCancerVO>> getPatientInfoProstateCancerList(@RequestParam String hospitalNumber,
                                                                           @RequestParam String gender,
                                                                           @RequestParam String idCard,
                                                                           @RequestParam String startTime,
                                                                           @RequestParam String endTime) {
        return patientService.getProstateCancerVOS(hospitalNumber, gender, idCard, startTime, endTime);
    }

    //    通过用户的权限和相关的查找变量来查找周期提醒信息
    @GetMapping("/getCycleRemindInfo")
    public Result<List<CycleRemindVO>> getCycleRemindInfo(@RequestParam String authority,
                                                          @RequestParam String hospitalNumber,
                                                          @RequestParam String idCard,
                                                          @RequestParam String cycleInterval,
                                                          @RequestParam String limitInterval,
                                                          @RequestParam String ifBeyondInterval) {
        return patientService.getCycleRemindInfo(authority, hospitalNumber, idCard, cycleInterval, limitInterval, ifBeyondInterval);
    }

    @PostMapping("/changePatientInterval")
    public Result changePatientInterval(@RequestBody UpdateIntervalDTO updateIntervalDTO) {
        return patientService.changePatientInterval(updateIntervalDTO.getHospitalNumber(),
                updateIntervalDTO.getNewInterval());
    }

    //待处理问题咨询量,按照最新时间排序
    @GetMapping("/getUnprocessedQuestion")
    public Result<List<QuestionVO>> getUnprocessedQuestion() {
        List<QuestionVO> questionVOList = questionService.getUnprocessedQuestion();
        return Result.success(questionVOList);
    }

    //待处理问题咨询量,按照最新时间排序
    @GetMapping("/getAllQuestion")
    public Result<List<QuestionVO>> getAllQuestion() {
        List<QuestionVO> questionVOList = questionService.getAllQuestion();
        return Result.success(questionVOList);
    }

    // 处理问题
    @PutMapping("/processQuestion")
    public Result processQuestion(@RequestBody AnswerDTO answerDTO) {
        questionService.processQuestion(answerDTO);
        return Result.success();
    }

    @PutMapping("/deleteQuestion")
    public Result deleteQuestion(Long id) {
        questionService.deleteQuestion(id);
        return Result.success();
    }

    @PostMapping("/addQuestion")
    public Result addQuestion(@RequestBody AnsQueDTO ansQueDTO) {
        questionService.insert(ansQueDTO);
        return Result.success();
    }

    @GetMapping("/getPatientExceptionList")
    public Result<List<PatientException>> getPatientExceptionList() {
        List<PatientException> patientExceptionList = patientExceptionService.getPatientExceptionList();
        return Result.success(patientExceptionList);
    }


    //127.0.0.1:8080/doctor/export
    @GetMapping("/export")
    public Result exportPatientInfos(HttpServletResponse response,
                                     @RequestParam(required = false) String startTime,
                                     @RequestParam(required = false) String endTime,
                                     @RequestParam(required = false, defaultValue = "default") String exportType) throws IOException, ParseException {
        // 解析 startTime 和 endTime
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null;
        Date endDate = null;

        if (StringUtils.isNotBlank(startTime)) {
            try {
                startDate = sdf.parse(startTime);
            } catch (ParseException e) {
                return Result.error("Invalid start time format. Please use yyyy-MM-dd.");
            }
        }

        if (StringUtils.isNotBlank(endTime)) {
            try {
                endDate = sdf.parse(endTime);
                // 设置 endTime 为当天的最后一刻
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endDate);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                endDate = calendar.getTime();
            } catch (ParseException e) {
                return Result.error("Invalid end time format. Please use yyyy-MM-dd.");
            }
        }
        String fileName = "测试";
        //需要合并的列
        int[] mergeColumns;
        List<?> dataList;
        Class<?> dataClass;
        //需要合并的列的
        int optLastColumnIdx = MergeColumnsConstants.OPT_LAST_COLUMN_IDX;
        int mergeRowStartIdx = MergeColumnsConstants.MERGE_ROW_START_IDX;
        switch (exportType) {
            case "type1":
                mergeColumns = MergeColumnsConstants.MERGE_COLUMNS_TYPE_1;
                dataList = patientService.getPatientInfoProstateCancerList(startDate, endDate);
                dataClass = PatientInfoProstateCancerVO.class;
                break;
            default:
                mergeColumns = MergeColumnsConstants.DEFAULT_MERGE_COLUMNS;
                dataList = patientService.getPatientInfoReturnVisitList(startDate, endDate);
                dataClass = PatientInfoReturnVisitListVO.class;
                break;
        }
        System.out.println(dataList);
        ExcelUtil.downloadExcel(response, fileName, dataList, dataClass, mergeColumns, optLastColumnIdx, mergeRowStartIdx);
        return Result.success();
    }

    //    用于user登录的接口
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody UserDTO userDTO) {
        User loginUser = userService.findByUserName(userDTO.getUsername());
        if (loginUser == null) {
            return Result.error("用户名错误");
        }
        if (Md5Util.getMD5String(userDTO.getPassword()).equals(loginUser.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            // 把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("authority", loginUser.getAuthority());
            result.put("id", loginUser.getId());
            return Result.success(result);
        }
        return Result.error("密码错误");
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody UserDTO userDTO) {
        // 1. 检查用户名是否已存在
        User existingUser = userService.findByUserName(userDTO.getUsername());
        if (existingUser != null) {
            return Result.error("用户名已存在");
        }
        // 2. 检查科室是否存在
        if (!userService.checkAuthorityExists(userDTO.getAuthority())) {
            return Result.error("科室不存在");
        }
        log.info(userDTO.getAuthority());
        // 3. 创建新用户对象
        User newUser = new User();
        newUser.setUsername(userDTO.getUsername());
        // 4. 使用MD5加密密码（与登录验证保持一致）
        String encryptedPassword = Md5Util.getMD5String(userDTO.getPassword());
        newUser.setPassword(encryptedPassword);
        newUser.setAuthority(userDTO.getAuthority());
        // 5. 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        newUser.setCreateTime(now);
        newUser.setUpdateTime(now);
        // 6. 插入数据库
        log.info(newUser.getAuthority());
        int result = userService.insertUser(newUser);
        if (result > 0) {
            return Result.success("注册成功");
        }
        return Result.error("系统错误，请稍后重试");
    }

    @GetMapping("/getAllDoctorInfo")
    public Result<List<User>> getAllDoctorInfo(@RequestParam String department) {
        List<User> userList = userService.getAllDoctorInfo(department);
        return Result.success(userList);
    }

    @PutMapping("/reset")
    public Result<String> reset(@RequestParam String yusernam, @RequestBody UserDTO userDTO) {
        // 1. 检查用户名是否已存在
        if (!yusernam.equals(userDTO.getUsername())) {
            User existingUser = userService.findByUserName(userDTO.getUsername());
            if (existingUser != null) {
                return Result.error("用户名已存在");
            }
        }
        // 2. 检查科室是否存在
        if (!userService.checkAuthorityExists(userDTO.getAuthority())) {
            return Result.error("科室不存在");
        }
        // 3. 创建新用户对象
        User newUser = new User();
        newUser.setUsername(userDTO.getUsername());
        // 4. 使用MD5加密密码（与登录验证保持一致）
        String encryptedPassword = Md5Util.getMD5String(userDTO.getPassword());
        newUser.setPassword(encryptedPassword);
        newUser.setAuthority(userDTO.getAuthority());
        // 5. 设置更新时间
        LocalDateTime now = LocalDateTime.now();
        newUser.setUpdateTime(now);
        // 6. 更新数据库
        int result = userService.resetUser(yusernam, newUser);
        if (result > 0) {
            return Result.success("修改成功");
        }
        return Result.error("系统错误，请稍后重试");
    }

    @DeleteMapping("/deletUser")
    public Result<String> deletUser(@RequestParam String username) {
        int result = userService.deletUser(username);
        if (result > 0) {
            return Result.success("删除成功");
        }
        return Result.error("系统错误，请稍后重试");
    }
}
